package com.company.huisuo.widget


import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.DashPathEffect
import android.graphics.Rect
import android.view.View
import androidx.annotation.ColorInt
import androidx.recyclerview.widget.RecyclerView

class DashedItemDecoration(
    context: Context,
    @ColorInt
    color: Int = 0x36707070, // 默认灰色
    private val strokeWidth: Float = 2f,        // 线宽
    private val dashWidth: Float = 15f,         // 实线长度
    private val dashGap: Float = 8f,            // 虚线间距
    private val orientation: Int = RecyclerView.VERTICAL,// 列表方向
    private val startPadding: Float = 0f,   // ← 左侧间距
    private val endPadding: Float = 0f      // ← 右侧间距
) : RecyclerView.ItemDecoration() {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        this.color = color
        style = Paint.Style.STROKE
        this.strokeWidth = this@DashedItemDecoration.strokeWidth
        pathEffect = DashPathEffect(floatArrayOf(dashWidth, dashGap), 0f)
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val childCount = parent.childCount
        if (orientation == RecyclerView.VERTICAL) {
            drawHorizontalLines(c, parent, childCount)
        } else {
            drawVerticalLines(c, parent, childCount)
        }
    }

    private fun drawHorizontalLines(canvas: Canvas, parent: RecyclerView, childCount: Int) {
        val left = parent.paddingLeft + startPadding
        val right = parent.width - parent.paddingRight - endPadding
        for (i in 0 until childCount - 1) {
            val child = parent.getChildAt(i)
            val params = child.layoutParams as RecyclerView.LayoutParams
            val top = (child.bottom + params.bottomMargin).toFloat()
            val y = top + strokeWidth / 2
            canvas.drawLine(left, y, right, y, paint)
        }
    }

    private fun drawVerticalLines(canvas: Canvas, parent: RecyclerView, childCount: Int) {
        val top = parent.paddingTop + startPadding
        val bottom = parent.height - parent.paddingBottom - endPadding
        for (i in 0 until childCount - 1) {
            val child = parent.getChildAt(i)
            val params = child.layoutParams as RecyclerView.LayoutParams
            val left = (child.right + params.rightMargin).toFloat()
            val x = left + strokeWidth / 2
            canvas.drawLine(x, top, x, bottom, paint)
        }
    }

    override fun getItemOffsets(
        outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
    ) {
        if (orientation == RecyclerView.VERTICAL) {
            outRect.bottom = strokeWidth.toInt() + 4
        } else {
            outRect.right = strokeWidth.toInt() + 4
        }
    }
}